<template>
  <div class="topic-audio">
    <div class="audio-right">
      <div class="icon" @click="play">
        <el-image
          v-show="isTimerPlaying"
          :src="require(`@/assets/images/public/exam_play_icon.png`)"
        ></el-image>
        <el-image
          v-show="!isTimerPlaying"
          :src="require(`@/assets/images/public/exam_pouse_icon.png`)"
        ></el-image>
      </div>
      <div class="text">听力文件</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BaseAudio',
  props: {
    fileurl: {
      type: String,
      default: ''
    },
    index: {
      type: Number,
      default: 0
    },
    palyIndex: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      audio: null,
      isTimerPlaying: false
    }
  },
  watch: {
    palyIndex() {
      if (this.palyIndex != this.index) {
        this.audio && this.audio.pause()
        this.isTimerPlaying = false
      }
    }
  },
  methods: {
    //播放暂停控制
    play() {
      if (this.audio.paused) {
        this.audio.play()
        this.isTimerPlaying = true
        this.$emit('play', this.index)
      } else {
        this.audio.pause()
        this.isTimerPlaying = false
      }
    },
    pause() {
      this.audio.pause()
      this.isTimerPlaying = false
    }
  },
  mounted() {
    this.audio = new Audio()
    this.audio.src = this.fileurl
    this.audio.onended = function() {
      this.isTimerPlaying = true
    }
  },
  destroyed() {
    if (this.audio) this.audio.pause()
  }
}
</script>

<style lang="scss" scoped>
.topic-audio {
  .audio-right {
    padding: 4px 10px 4px 4px;
    display: inline-flex;
    align-items: center;
    @include edu-color-primary(background-color);
    border-radius: 15px;
    .icon {
      width: 22px;
      height: 22px;
      .el-image {
        width: 100%;
        height: 100%;
      }
    }
    .text {
      margin-left: 5px;
      font-size: 12px;
      font-weight: 400;
      color: #ffffff;
    }
  }
}
</style>
